package com.skywalker.common;

import com.jfinal.config.*;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.json.MixedJsonFactory;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.template.Engine;
import com.skywalker.common.plugin.j2cache.J2Cache;
import com.skywalker.common.plugin.j2cache.J2CachePlugin;
import com.skywalker.common.model._MappingKit;
import com.skywalker.j2cache.J2CacheController;

/**
 * @user: skywalker
 * @date: 2019/4/13 9:18
 * @description: 借鉴了 小徐同学 / JFinal-vue-element-admin项目
 */
public class SysConfig extends JFinalConfig {

    private static Prop p = loadConfig();

    private static Prop loadConfig() {
        return PropKit.use("sys_config.txt").appendIfExists("config.txt");
    }

    @Override
    public void configConstant(Constants me) {
        loadConfig();
        me.setDevMode(p.getBoolean("devMode", false));
        me.setJsonFactory(MixedJsonFactory.me());
        me.setInjectDependency(true);
    }

    @Override
    public void configRoute(Routes me) {
        me.add("j2cache", J2CacheController.class, "j2cache");
    }

    /**
     * 抽取成独立的方法，便于 _Generator 中重用该方法，减少代码冗余
     */
    public static DruidPlugin getDruidPlugin() {
        loadConfig();
        return new DruidPlugin(p.get("jdbcUrl"), p.get("user"), p.get("password").trim());
    }

    @Override
    public void configPlugin(Plugins me) {
        // 配置数据库连接池插件
        DruidPlugin druidPlugin = getDruidPlugin();
        // orm映射 配置ActiveRecord插件
        ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
        arp.setShowSql(p.getBoolean("devMode", false));
        arp.setDialect(new MysqlDialect());
        arp.getEngine().setToClassPathSourceFactory();
        arp.addSqlTemplate("/sql/all_sqls.sql");
        // 设置arp的cache类型
        arp.setCache(new J2Cache());

        _MappingKit.mapping(arp);
        me.add(druidPlugin);
        me.add(arp);

        me.add(new J2CachePlugin());
    }

    @Override
    public void configInterceptor(Interceptors me) {

    }

    @Override
    public void configHandler(Handlers me) {
        me.add(new ContextPathHandler("BASE_PATH"));
    }


    @Override
    public void configEngine(Engine me) {

    }

}
